// #ifdef APP-PLUS
// 副屏插件------------
var LySDKModule = uni.requireNativePlugin("LY028-NativeSdk");
// 商米插件
const sunmiCashboxPlugin = uni.requireNativePlugin(
  "Tellsea-SunmiCashboxPlugin"
);
// #endif
// 打印机插件------开始------
import { UsbConnect } from "@/utils/UsbConnect.js";
import { PrinterManager } from "@/utils/PrinterManager.js";
import { PrinterUtils } from "@/utils/PrinterUtils.js";
//定义变量
const usbConnect = new UsbConnect();
const printerUtils = new PrinterUtils();
const printerManager = new PrinterManager();
// 打印机插件------结束------

let timer;
let flag;
export default {
  // 打开副屏
  openSecondScreen () {
    return new Promise((resolve, reject) => {
      LySDKModule.openSecondScreen(
        {
          url: plus.io.convertLocalFileSystemURL("/static/html/index.html"), //副屏url
        },
        (ret) => {
          console.log("打开副屏", ret);
          resolve(ret);
        }
      );
    })

  },
  // 关闭副屏
  closeSecondScreen () {
    LySDKModule.closeSecondScreen();
  },
  // 发送数据到副屏
  sendDataToSecondScreen (data) {
    return new Promise((resolve, reject) => {
      LySDKModule.sendDataToSecondScreen(
        data,
        (ret) => {
          console.log("发送数据到副屏", data, ret);
          resolve(ret);
        }
      );
    });

  },
  connectQianxiang () {
    // 连接钱箱设备
    sunmiCashboxPlugin.connect((e) => {
      let res = JSON.parse(e);
      if (res.code == 200) {
        console.log(res.msg);

      } else {
        console.log(res.msg)
      }
    });
  },
  // 打开钱箱
  openQianxiang () {
    // 打开钱箱
    sunmiCashboxPlugin.openDrawer((e) => {
      let res = JSON.parse(e);
      if (res.code == 200) {
        uni.$u.toast(res.msg)
      } else {
        uni.$u.toast(res.msg)
      }
    });
  },
  // 获取打印机设备列表  并 连接打印机
  async onConnect () {
    try {
      // 获取所有usb打印机设备
      let usbDevicesRes = await usbConnect.getAllUsbPrinterDevices();
      if (usbDevicesRes.code != 0) return uni.$u.toast(usbDevicesRes.message)
      if (!usbDevicesRes.data.list.length) return uni.$u.toast("未获取到打印机设备");
      let deviceInfo = usbDevicesRes.data.list[0];
      // 连接打印机
      usbConnect.connect(deviceInfo.deviceName);
    } catch (e) {
    }
  },
  // 打印小票
  async printNote () {
    printerUtils.printNote()
  },
  // 查询打印机状态
  getPrinterStatus () {
    printerManager.getCurrentStatus().then((res) => {
      if (res.code == 0) {
        let data = res.data || {};
        let status = data.status;
        if (status == 0) {
          uni.$u.toast("打印机状态正常");
        } else if (status == -1) {
          uni.$u.toast("接收数据失败");
        } else if (status == -2) {
          uni.$u.toast("打印机缺纸");
        } else if (status == -3) {
          uni.$u.toast("打印机纸将尽");
        } else if (status == -4) {
          uni.$u.toast("打印机开盖");
        } else if (status == -5) {
          uni.$u.toast("发送数据失败");
        } else {
          uni.$u.toast("未知状态");
        }
      } else {
        uni.$u.toast(res.message);
      }
    });
  },
  getSn () {
    // #ifdef APP-PLUS
    var Build = plus.android.importClass("android.os.Build");
    var serial = '';

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { // Android 9.0及以上
      var Manifest = plus.android.importClass("android.Manifest");
      var MainActivity = plus.android.runtimeMainActivity();
      var ArrPermissions = [Manifest.permission.READ_PHONE_STATE];

      function PermissionCheck (permission) {
        if (Build.VERSION.SDK_INT >= 23) {
          if (MainActivity.checkSelfPermission(permission) == -1) {
            return false;
          }
        }
        return true;
      }

      function PermissionRequest (Arr) {
        var REQUEST_CODE_CONTACT = 101;
        if (Build.VERSION.SDK_INT >= 23) {
          MainActivity.requestPermissions(Arr, REQUEST_CODE_CONTACT);
        }
      }

      if (!PermissionCheck(ArrPermissions[0])) {
        PermissionRequest(ArrPermissions);
      } else {
        serial = Build.getSerial();
      }
    } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) { // Android 8.0及以上
      if (Build.SERIAL) {
        serial = Build.SERIAL;
      }
    } else {
      // 对于Android 8.0以下版本，可以使用SystemProperties获取SN
      var SystemProperties = plus.android.importClass("android.os.SystemProperties");
      serial = SystemProperties.get('ro.serialno');
    }
    return serial
    // #endif
  },
  // getAndroidDeviceInfo (callback) {
  //   // #ifdef APP-PLUS

  //   if (plus.os.name !== 'Android') {
  //     console.warn("当前不是 Android 设备");
  //     callback && callback(null);
  //     return;
  //   }

  //   // 申请权限（部分字段如 IMEI/SN 需要）
  //   const permissions = [
  //     'android.permission.READ_PHONE_STATE'
  //   ];

  //   plus.android.requestPermissions(permissions, (res) => {
  //     if (res.granted.length > 0) {
  //       // 导入原生类
  //       const Build = plus.android.importClass("android.os.Build");
  //       const Settings = plus.android.importClass("android.provider.Settings");
  //       const main = plus.android.runtimeMainActivity();
  //       const contentResolver = main.getContentResolver();

  //       // 获取相关信息
  //       const sn = Build.getSerial(); // 设备序列号
  //       const model = Build.MODEL;    // 设备型号
  //       const brand = Build.BRAND;    // 品牌
  //       const manufacturer = Build.MANUFACTURER; // 厂商
  //       const androidId = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID);

  //       // 获取 IMEI（新版本可能无法返回）
  //       let imei = '';
  //       try {
  //         const TelephonyManager = plus.android.importClass("android.telephony.TelephonyManager");
  //         const telManager = main.getSystemService(main.TELEPHONY_SERVICE);
  //         imei = telManager.getImei ? telManager.getImei() : '不支持';
  //       } catch (e) {
  //         imei = '获取失败';
  //       }

  //       // 获取 UUID（plus 提供的唯一设备标识）
  //       const uuid = plus.device.uuid;

  //       // 返回信息
  //       const deviceInfo = {
  //         sn,
  //         model,
  //         brand,
  //         manufacturer,
  //         androidId,
  //         imei,
  //         uuid,
  //         appVersion: '', //app版本号
  //         sysVersion: '', //系统版本号
  //         homeScreen: '',//主屏幕分辨率
  //         secondaryScreen: '',//副屏幕分辨率
  //       };

  //       console.log('📱 设备信息：', deviceInfo);
  //       callback && callback(deviceInfo);
  //     } else {
  //       console.warn("权限未授予，无法获取完整设备信息");
  //       callback && callback(null);
  //     }
  //   }, (err) => {
  //     console.error("权限请求失败", err);
  //     callback && callback(null);
  //   });

  //   // #endif

  // },
  getAndroidDeviceInfo (callback) {
    // #ifdef APP-PLUS
    if (plus.os.name !== 'Android') {
      console.warn("当前不是 Android 设备");
      callback && callback(null);
      return;
    }

    const permissions = ['android.permission.READ_PHONE_STATE'];

    plus.android.requestPermissions(permissions, (res) => {
      if (res.granted.length > 0) {
        const Build = plus.android.importClass("android.os.Build");
        const Settings = plus.android.importClass("android.provider.Settings");
        const main = plus.android.runtimeMainActivity();
        const contentResolver = main.getContentResolver();

        const sn = Build.getSerial();
        const model = Build.MODEL;
        const brand = Build.BRAND;
        const manufacturer = Build.MANUFACTURER;
        const androidId = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID);
        const sysVersion = Build.VERSION.RELEASE;
        const apiLevel = Build.VERSION.SDK_INT;
        const homeScreen = plus.screen.resolutionHeight + "x" + plus.screen.resolutionWidth;

        // let secondaryScreen = '';
        // try {
        //   const DisplayManager = plus.android.importClass("android.hardware.display.DisplayManager");
        //   const DisplayMetrics = plus.android.importClass("android.util.DisplayMetrics");
        //   const main = plus.android.runtimeMainActivity();
        //   const displayManager = main.getSystemService(main.DISPLAY_SERVICE);
        //   const displays = displayManager.getDisplays();

        //   if (displays.length > 1) {
        //     const dm = new DisplayMetrics();
        //     const secondDisplay = displays[1];
        //     secondDisplay.getMetrics(dm);
        //     secondaryScreen = `${dm.widthPixels}x${dm.heightPixels}`;
        //   }
        // } catch (e) {
        //   console.warn("获取副屏分辨率失败：", e);
        // }

        // // 获取 IMEI
        // let imei = '';
        // try {
        //   const TelephonyManager = plus.android.importClass("android.telephony.TelephonyManager");
        //   const telManager = main.getSystemService(main.TELEPHONY_SERVICE);
        //   imei = telManager.getImei ? telManager.getImei() : '不支持';
        // } catch (e) {
        //   imei = '获取失败';
        // }

        const uuid = plus.device.uuid;
        const appVersion = plus.runtime.version;
        const packageName = plus.runtime.packageName;

        const deviceInfo = {
          sn,
          model,
          brand,
          manufacturer,
          androidId,
          // imei,
          uuid,
          appVersion,
          sysVersion,
          apiLevel,
          packageName,
          homeScreen,
          // secondaryScreen
        };

        console.log('📱 设备信息：', deviceInfo);
        callback && callback(deviceInfo);
      } else {
        console.warn("权限未授予，无法获取完整设备信息");
        callback && callback(null);
      }
    }, (err) => {
      console.error("权限请求失败", err);
      callback && callback(null);
    });
    // #endif
  },


  // 判断对象是否为空
  isEmpty (object) {
    for (const name in object) {
      return false
    }
    return true
  },

  //加
  FloatAdd (arg1, arg2) {
    if (!arg1) arg1 = 0;
    if (!arg2) arg2 = 0;

    let r1, r2;
    try {
      r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
      r2 = 0;
    }
    const c = Math.abs(r1 - r2);
    const m = Math.pow(10, Math.max(r1, r2));
    if (c > 0) {
      const cm = Math.pow(10, c);
      if (r1 > r2) {
        arg1 = Number(arg1.toString().replace(".", ""));
        arg2 = Number(arg2.toString().replace(".", "")) * cm;
      } else {
        arg1 = Number(arg1.toString().replace(".", "")) * cm;
        arg2 = Number(arg2.toString().replace(".", ""));
      }
    } else {
      arg1 = Number(arg1.toString().replace(".", ""));
      arg2 = Number(arg2.toString().replace(".", ""));
    }
    return (arg1 + arg2) / m;
  },

  //减
  FloatSub (arg1, arg2) {
    if (!arg1) arg1 = 0;
    if (!arg2) arg2 = 0;

    let r1, r2;
    try {
      r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
      r2 = 0;
    }
    const m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
    const n = r1 >= r2 ? r1 : r2;
    return Number(((arg1 * m - arg2 * m) / m).toFixed(n));
  },

  //乘
  FloatMul (arg1, arg2) {
    if (!arg1) arg1 = 0;
    if (!arg2) arg2 = 0;

    let m = 0;
    const s1 = arg1.toString();
    const s2 = arg2.toString();
    try {
      m += s1.split(".")[1].length;
    } catch (e) { }
    try {
      m += s2.split(".")[1].length;
    } catch (e) { }
    return (
      (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
      Math.pow(10, m)
    );
  },

  //除
  FloatDiv (arg1, arg2) {
    if (!arg1) arg1 = 0;
    if (!arg2) arg2 = 0;

    let t1 = 0,
      t2 = 0;
    try {
      t1 = arg1.toString().split(".")[1].length;
    } catch (e) { }
    try {
      t2 = arg2.toString().split(".")[1].length;
    } catch (e) { }

    const r1 = Number(arg1.toString().replace(".", ""));
    const r2 = Number(arg2.toString().replace(".", ""));
    // 0/0 = NaN
    return (r1 / r2 || 0) * Math.pow(10, t2 - t1);
  },
  // 处理obj数据剔除无用数据
  filterFormData (data, obj = {}) {
    if (this.isEmpty(obj)) return data
    // 数组处理
    if (Array.isArray(data)) {
      return data.map((item) => {
        const newItem = {}
        for (const key in obj) {
          let v = item[key]
          if (v === '' || v === null) v = undefined
          newItem[key] = v
        }
        return newItem
      })
    }
    // 对象处理
    else if (typeof data === 'object') {
      const newObj = {}
      for (const key in obj) {
        let v = data[key]
        if (v === '' || v === null) v = undefined
        newObj[key] = v
      }
      return newObj
    } else {
      return data
    }
  },
  // 跳转二次封装，方便后续处理跳转逻辑
  toUrl (url, type) {
    // 如果是tabbar页面必须用switch跳转
    const tabBarList = [
      // "/pages/index/index",
      // "/pages/home/home",
      // "pages/energy_chart/energy_chart",
    ];
    // 所有跳转switchTab页面储存地址携带的参数 && 跳转方式如果不能传reLaunch,否则不储存携带参数
    if (
      tabBarList.some((item) => url.indexOf(item) !== -1) &&
      type != "reLaunch"
    ) {
      if (url.indexOf("?") !== -1) {
        uni.setStorageSync("switchTabParams", url.split("?"));
      }
      uni.switchTab({
        url: url,
      });
      return;
    }

    if (type == "redirectTo") {
      uni.redirectTo({
        url,
      });
    } else if (type == "reLaunch") {
      uni.reLaunch({
        url,
      });
    } else {
      uni.navigateTo({
        url,
      });
    }
  },
  // 后退页面
  toBack (num = 1) {
    let current = getCurrentPages();

    if (current.length <= 1) {
      // console.log('当前没有上一页,将跳转至首页');
      this.toUrl('/pages/index/index')
    } else {
      uni.navigateBack({
        delta: num
      })
    }

  },
  // showModal封装为promise对象
  showModalAsync (params) {
    return new Promise((resolve, reject) => {
      uni.showModal({
        title: '提示',
        cancelText: '取消',
        confirmText: '确定',
        success: (result) => {
          if (!result.confirm) reject(result.confirm)
          else resolve(result);
        },
        fail: (err) => {
          reject(err);
        },
        complete: () => { },
        ...params,
      });
    });
  },

  /**
   * 节流原理：在一定时间内，只能触发一次
   *
   * @param {Function} func 要执行的回调函数
   * @param {Number} wait 延时的时间
   * @param {Boolean} immediate 是否立即执行
   * @return null
   */
  throttle (func, wait = 500, immediate = true) {
    if (immediate) {
      if (!flag) {
        flag = true
        // 如果是立即执行，则在wait毫秒内开始时执行
        typeof func === 'function' && func()
        timer = setTimeout(() => {
          flag = false
        }, wait)
      }
    } else if (!flag) {
      flag = true
      // 如果是非立即执行，则在wait毫秒内的结束处执行
      timer = setTimeout(() => {
        flag = false
        typeof func === 'function' && func()
      }, wait)
    }
  },
  // 处理条码是多条只显示第一条
  barCodeNoe (text) {
    if (text) {
      let a = text.split(',')
      return a[0] || '-'
    }
    return '-'
  },
  // 获取基础sku
  initSku (product = {}) {

    if (Array.isArray(product.skus) && product.skus.length > 0) {

      let sku = product.skus.find(item => item.primaryUnit)
      return sku
    }
    return {}
  }
}
